# -*- coding: utf-8 -*-
# @Time    : 2022/1/20 21:16
# @Author  : Mr.Ye
# @Email   : a3289748713@163.com
# @File    : __init__.py.py
# @Software: PyCharm

from flask import Flask
import os
from flask_sqlalchemy import SQLAlchemy
from MyVideo.configs import config
from flask_wtf import CSRFProtect
from flask_login import LoginManager

app = Flask(__name__)

# 配置模式
PATTER = os.getenv('PATTER') or 'default'
# 数据库配置
MYSQL_HOST = os.getenv('MYSQL_HOST') or '127.0.0.1'
MYSQL_USER = os.getenv('MYSQL_USER') or 'root'
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD') or 'sy_root'
MYSQL_DATABASE = os.getenv('MYSQL_DATABASE') or 'video'
SECRET_KEY = os.getenv('SECRET_KEY') or '79537d00f4834892986f09a100aa1edf'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{user}:{password}@{host}:3306/{name}'.format(user=MYSQL_USER,
                                                                                        password=MYSQL_PASSWORD,
                                                                                        name=MYSQL_DATABASE,
                                                                                        host=MYSQL_HOST)

app.config.from_object(config[PATTER])
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI  # 配置数据URI
# 关于这个设置，看这个解释: http://www.dovov.com/sqlalchemy_track_modifications.html
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI  # 配置数据URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = False

# 在登录的时候有用到
app.config["SECRET_KEY"] = SECRET_KEY
# 将配置后的app绑定SQL
app.debug = True

CSRFProtect(app)
db = SQLAlchemy(app)

login_manager = LoginManager()
login_manager.init_app(app)


@login_manager.user_loader
def load_user(user_id):
    from MyVideo.models import Admin
    user = db.session.query(Admin).get(user_id)
    return user


# 视图
from MyVideo.admin import admin

app.register_blueprint(admin, url_prefix="/admin")
